package uk.co.nazz.f21mc_a2.ui;

import java.util.Calendar;

import uk.co.nazz.f21mc_a2.DiaryApplication;
import uk.co.nazz.f21mc_a2.R;
import uk.co.nazz.f21mc_a2.diary.Event;
import uk.co.nazz.f21mc_a2.utils.ExtendedArrayAdapter;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Events;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * 
 * @author Andrew Sokes Activity to display a list of events
 * 
 */
public class EventsList extends Activity implements OnItemClickListener {

	private DiaryApplication application;
	private String[] projection;
	private String selection;
	private String[] seletionArgs;
	private String sortOrder;
	private ListView eventsListView;
	private Event[] events;

	// This is the Adapter being used to display the list's data
	// as icons and text
	private ExtendedArrayAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (DiaryApplication) this.getApplication();

		setContentView(R.layout.events_list);

		eventsListView = (ListView) findViewById(R.id.events_listview);
		eventsListView.setOnItemClickListener(this);

	}

	// get the list of event objects and return as an array
	private Event[] addEvents() {
		// the events columns to retrieve
		projection = new String[] { Events._ID, Events.TITLE, Events.DTSTART,
				Events.RRULE, Events.HAS_ATTENDEE_DATA };

		// Select criteria to display events for the specified calendar which
		// haven't been deleted
		selection = "(" + Events.CALENDAR_ID + " =? ) AND (deleted != 1)";
		int calId = application.getDiary().getDiaryId();
		seletionArgs = new String[] { Integer.toString(calId) };
		// sort by start date
		sortOrder = Events.DTSTART + " ASC";

		// create the cursor
		Cursor cursor = getContentResolver().query(Events.CONTENT_URI,
				projection, selection, seletionArgs, sortOrder);

		// iterate through the cursor and add the events to the array
		Event[] events = new Event[cursor.getCount()];
		int i = 0;
		while (cursor.moveToNext()) {
			String title = cursor
					.getString(cursor.getColumnIndex(Events.TITLE));
			long eventId = Long.parseLong(cursor.getString(cursor
					.getColumnIndex(Events._ID)));
			Calendar start = Calendar.getInstance();
			start.setTimeInMillis(Long.parseLong(cursor.getString(cursor
					.getColumnIndex(Events.DTSTART))));
			Boolean isRecurring = cursor.getString(
					cursor.getColumnIndex(Events.RRULE)).length() > 0;

			Event e = new Event(start, title, eventId, isRecurring,
					attendeeCount(eventId));
			events[i] = e;
			i++;
		}
		return events;

	}

	// handle the click event of the list and start an intent to display the
	// selected event
	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		String eventId = Long.toString(adapter.getItem(position).getId());
		Intent intent = new Intent(this, ViewEventActivity.class);
		intent.putExtra("eventId", eventId);
		startActivity(intent);

	}

	// private method to query number of attendees for an event
	private int attendeeCount(Long eventId) {
		// query for the attendees
		String[] attendeeProjection = { Attendees.ATTENDEE_NAME };
		String attendeeSelection = Attendees.EVENT_ID + "=?";
		String[] attendeeseletionArgs = { Long.toString(eventId) };

		Cursor attendeeCursor = getContentResolver().query(
				Attendees.CONTENT_URI, attendeeProjection, attendeeSelection,
				attendeeseletionArgs, null);

		return attendeeCursor.getCount();

	}

	// build/refresh the UI
	@Override
	protected void onResume() {
		super.onResume();
		events = addEvents();
		// Create an empty adapter
		adapter = new ExtendedArrayAdapter(this, events);
		adapter.notifyDataSetChanged();
		if (adapter.getCount() > 0) {
			eventsListView.setAdapter(adapter);
		} else {
			String[] s = { "No event data to display" };
			eventsListView.setAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, s));

		}
	}

}